package com.chapter1.basic.chain;

/** 
 * @ClassName: Link 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author minjun minjun@bw30.com
 * @date 2015-2-12 下午3:05:37 
 *  
 */
public class Link<Item>{
	
	private Node first;
	
	private Node last;
	
	private int index;

	private class Node{
		Item item;
		
		Node next;
	}
	
	public boolean isEmpty(){
		return index==0;
	}
	
	public void add(Item item){
		Node oldLast=last;
		last=new Node();
		last.item=item;
		last.next=null;
		if(isEmpty()){
			first=last;
		}else{
			oldLast.next=last;
		}
		index++;
	}
	
	public Item removeLast(){
		if(isEmpty()){
			return null;
		}else if(index==1){
			Item item=first.item;
			first=null;
			index--;
			return item;
		}else{
			Node n=first;
			for(int i=0;i<index-2;i++){
				first=first.next;
			}
			Item item=first.next.item;
			first.next=first.next.next;
			first=n;
			index--;
			return item;
		}
	}
}
